package Leetcode.Stack;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Queue;

/**
 * @Author: kirito
 * @Date: 2024/4/26 22:10
 * @Description:
 *
 */

public class Infixexpression {
    /**
     * 中缀转后缀
     *  1.遇到操作数
     *      入栈
     *  2.遇到界限符号
     *      左括号入栈
     *      右括号，依次弹出栈内运算符并加入后缀表达式
     *          直到弹出左括号为止
     *  3.遇到运算符号
     *      依次弹出优先级高于或等于当前运算符的所有运算符
     *   并加入后缀表达式
     *      如果碰到左括号或者栈空就停止
     *      当前运算符入栈
     * @param s 中缀
     * @return  后缀
     */
    private String after(String s) {
        int len = s.length();
        char[] chars = s.toCharArray();
        Deque<Character> stack = new ArrayDeque<>();
        StringBuilder ans = new StringBuilder();
        for (int i = 0; i < len; i++) {
            char c = chars[i];
            if (!isBoundary(c) && !isOperator(c)) {
                stack.push(c);
            }
            if (c =='(') {
                stack.push(c);
            }
            if (c == ')') {
                while (!stack.isEmpty()) {
                    Character pop = stack.pop();
                    if (pop == 'c') {
                        break;
                    }
                    ans.append(pop);
                }
            }
        }
        return ans.toString();
    }

    private boolean isOperator(char c) {
        return c == '+'
            || c == '-'
            || c == '*'
            || c == '/';
    }

    private boolean isBoundary(char c) {
        return c == '('
            || c == ')';
    }
}
